package cn.ld.module.infra.dal.mapper.logger;

import cn.ld.framework.common.pojo.PageResult;
import cn.ld.framework.mybatis.core.mapper.BaseMapperX;
import cn.ld.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.ld.module.infra.controller.admin.logger.vo.apiaccesslog.ApiAccessLogPageInVO;
import cn.ld.module.infra.dal.entity.logger.ApiAccessLogEntity;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.time.LocalDateTime;

/**
 * API 访问日志 Mapper
 *
 * @author 蓝盾
 */
@Mapper
public interface ApiAccessLogMapper extends BaseMapperX<ApiAccessLogEntity> {

    default PageResult<ApiAccessLogEntity> selectPage(ApiAccessLogPageInVO inVO) {
        return selectPage(inVO, new LambdaQueryWrapperX<ApiAccessLogEntity>()
                .eqIfPresent(ApiAccessLogEntity::getUserId, inVO.getUserId())
                .eqIfPresent(ApiAccessLogEntity::getUserType, inVO.getUserType())
                .eqIfPresent(ApiAccessLogEntity::getApplicationName, inVO.getApplicationName())
                .likeIfPresent(ApiAccessLogEntity::getRequestUrl, inVO.getRequestUrl())
                .betweenIfPresent(ApiAccessLogEntity::getBeginTime, inVO.getBeginTime())
                .geIfPresent(ApiAccessLogEntity::getDuration, inVO.getDuration())
                .eqIfPresent(ApiAccessLogEntity::getResultCode, inVO.getResultCode())
                .orderByDesc(ApiAccessLogEntity::getId)
        );
    }

    /**
     * 物理删除指定时间之前的日志
     *
     * @param createTime 最大时间
     * @param limit 删除条数，防止一次删除太多
     * @return 删除条数
     */
    @Delete("DELETE FROM infra_api_access_log WHERE create_time < #{createTime} LIMIT #{limit}")
    Integer deleteByCreateTimeLt(@Param("createTime") LocalDateTime createTime, @Param("limit") Integer limit);

}
